<template>
  <div>
    <div class="top_option" style="margin-bottom: 10px;">
      <el-button @click="addBanner" type="primary">新增轮播图</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%" highlight-current-row
      :header-cell-style="{ background: 'rgb(179, 108, 255)', color: '#fff' }">
      <el-table-column align="center" prop="bannerName" label="轮播图名称" />
      <el-table-column align="center" prop="bannerImage" label="轮播图">
        <template #default="scope">
          <el-image class="tableData_image" :src="scope.row.bannerImage"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createtime" label="创建时间" :formatter="formatDate">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <el-button size="small" type="warning" @click="editBanner(scope.row.id)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteBanner(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-dialog v-model="dialogVisible" :title="title" width="60%">
        <el-form ref="banner" :model="form" :rules="rules" @submit.native.prevent="onSubmit" label-width="120px">
          <el-form-item label="轮播图名称" prop="bannerName">
            <el-input maxlength="30" v-model="form.bannerName" />
          </el-form-item>
          <el-form-item label="轮播图" prop="bannerImage">
            <el-upload :headers="headers" class="upload_image" :before-upload="beforeAvatarUpload"
              :http-request="uploadImage" :show-file-list="false">
              <el-image :src="form.bannerImage" v-if="form.bannerImage" class="bannerImage" />
              <el-icon :size="35" color="#a8abb2" v-else>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { imageUpload, BannerAddApi, BannerListApi, BannerEditApi, BannerDetailApi, BannerDeleteApi } from '@/api/index'
import { ElMessage } from 'element-plus'
const tableData = ref([]);
const dialogVisible = ref(false);
const title = ref('');
const form = ref({
  bannerImage: '',
  bannerName: ''
});

// 假设你需要在组件挂载时从 localStorage 获取 token  
const headers = computed(() => ({
  Authorization: localStorage.getItem("token"),
}));

// 验证规则也可以是响应式的，但在这里我们直接定义它们  
const rules = {
  bannerName: [
    { required: true, message: "轮播图名称不能为空", trigger: "blur" },
  ],
  bannerImage: [{ required: true, message: "轮播图不能为空", trigger: "blur" }],
}

const formatDate = (value) => {
  const date = new Date(value.createtime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const addBanner = () => {
  dialogVisible.value = true
  title.value = '添加轮播图'
  form.value = {}
}

const getBannerList = () => {
  BannerListApi().then(res => {
    if (res.data.code == 1) {
      tableData.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}
const editBanner = (id) => {
  title.value = '修改轮播图'
  BannerDetailApi(id).then(res => {

    if (res.data.code == 1) {
      form.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
    }
  })
  dialogVisible.value = true
}
const deleteBanner = (id) => {
  BannerDeleteApi({ id: id }).then((res) => {
    if (res.data.code == 1) {
      ElMessage({
        type: "success",
        message: res.data.msg,
        duration: 1500,
        onClose: () => {
          getBannerList();
        },
      });
    } else {
      ElMessage({
        type: "error",
        message: res.data.msg,
      });
    }
  });
}
const banner = ref(null)
const onSubmit = () => {
  banner.value.validate((valid) => {
    if (valid) {
      if (form.value.id) {
        BannerEditApi(form.value).then(res => {
          if (res.data.code == 1) {
            ElMessage({
              type: 'success',
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                dialogVisible.value = false
                form.value = {}
                getBannerList()
              }
            })
          } else {
            ElMessage({
              type: 'error',
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                dialogVisible.value = false
                form.value = {}
                getBannerList()
              }
            })
          }
        })
      } else {
        BannerAddApi(form.value).then(res => {
          if (res.data.code == 1) {
            ElMessage({
              type: 'success',
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                dialogVisible.value = false
                form.value = {}
                getBannerList()
              }
            })
          } else {
            ElMessage({
              type: 'error',
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                dialogVisible.value = false
                form.value = {}
                getBannerList()
              }
            })
          }
        })
      }
    }
  })
}
const uploadImage = (param) => {
  // 获取上传的文件名
  var file = param.file;
  //发送请求的参数格式为FormData
  const formData = new FormData();
  formData.append("file", file);
  // 调用param中的钩子函数处理各种情况，这样就可以用在组件中用钩子了。也可以用res.code==200来进行判断处理各种情况
  imageUpload(formData, param)
    .then((res) => {
      if (res.data.code == 1) {
        console.log(res);
        form.value.bannerImage = res.data.data.path
      }
    })
    .catch((err) => {
      param.onError(err);
    });
}
const beforeAvatarUpload = (file) => {
  console.log(file.type);

}
getBannerList()
</script>

<style lang="scss" scoped>
.top_option {
    background-color: white;
    padding: 20px;
    margin-bottom: 20px;
}

.tableData_image {
    width: 180px;
    height: 100px;
}

.bannerImage {
    width: 200px;
    height: 200px;
}
</style>